package com.bob.clan.wxconnector.wxService;

import com.alibaba.fastjson.JSONObject;
import com.bob.clan.wxconnector.DTO.ModelMsgDTO;
import com.bob.clan.wxconnector.config.WxServerConfig;
import com.bob.clan.wxconnector.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用于与粉丝发送消息
 */
@Slf4j
@Service
public class WxModelMsgService {
    @Autowired
    private WxServerConfig wxServerConfig;
    @Autowired
    private TokenService tokenService;

    //向族谱管理员发送成员族谱成员的申请
    public void sendAppClanMemberMsg(String toUserOpenid, JSONObject msg){
        ModelMsgDTO msgVO = new ModelMsgDTO();
        msgVO.setSysCode("clan");
        msgVO.setTemplate_id("tFVYxSycxjeNQyvI7zjh0vTqSGKzr8jNdoPIG0ivT20");
        msgVO.setUrl("https://www.baidu.com");
        msgVO.setTouser(toUserOpenid);
        msgVO.setData(msg);
        this.sendModelMsg(msgVO);
    }

    //发送模板消息
    public void sendModelMsg(ModelMsgDTO msgVO){
        String token = tokenService.getToken(msgVO.getSysCode());
        String url =wxServerConfig.getUrlByToken(wxServerConfig.getModelMsgUrl(), token);

        //组装数据
        JSONObject actionJson = setupMsgJson(msgVO);
        log.info("send model msg =" + actionJson);
        JSONObject retJson = HttpUtil.doPostSSL(url, actionJson);
        log.info("wechat back json=" + retJson);
    }

    private JSONObject setupMsgJson(ModelMsgDTO msgVO){
        JSONObject actionJson = new JSONObject();
        actionJson.put("touser", msgVO.getTouser());
        actionJson.put("template_id", msgVO.getTemplate_id());
        actionJson.put("url", msgVO.getUrl());
        actionJson.put("data", msgVO.getData());
        return actionJson;
    }
}
